<html>
  <head>
    <title>组件的生命周期函数(新)</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/javascript" src="../../js/react_v18.2.0/react.development.js"></script>
    <script type="text/javascript" src="../../js/react_v18.2.0/react-dom.development.js"></script>
    <script type="text/javascript" src="../../js/babel.min.js"></script>
    <script type="text/babel">
      class Count extends React.Component {
        constructor(props) {
          super(props);
          this.state = { count: 0 };
        }

        componentDidMount() {
          console.log('Count---componentDidMount');
        }

        componentWillUnmount() {
          console.log('Count---componentWillUnmount');
        }

        shouldComponentUpdate() {
          console.log('Count---shouldComponentUpdate');
          return true;
        }

        componentDidUpdate(prevProps, prevState, snapshotValue) {
          console.log('Count---componentDidUpdate', { prevProps, prevState, snapshotValue });
        }

        // 若state的值在任何时候都取决于props，很少用到
        static getDerivedStateFromProps(props, state) {
          console.log('Count---getDerivedStateFromProps', { props, state });
          return null;
        }

        getSnapshotBeforeUpdate(prevProps, prevState) {
          console.log('Count---getSnapshotBeforeUpdate', { prevProps, prevState });
          return { name: 'Judith' };
        }

        add = () => {
          const { count } = this.state;
          this.setState({ count: count + 1 });
        }

        unmount = () => {
          ReactDOM.unmountComponentAtNode(document.getElementById('root'));
        }

        force = () => {
          this.forceUpdate();
        }

        render() {
          console.log('Count---render');
          const { count } = this.state;

          return (
            <div>
              当前值：{count} <br />
              <button onClick={this.add}>点击加1</button> <br />
              <button onClick={this.unmount}>卸载组件</button> <br />
              <button onClick={this.force}>不更新state，强制更新</button>
            </div>
          );
        }
      }

      ReactDOM.render(<Count count={100} />, document.getElementById('root'));
    </script>
  </body>
</html>
